package io.renren.modules.dangan.utils;

import cn.hutool.core.io.FileUtil;
import io.renren.modules.dangan.entity.DaServerEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.*;


@Component
@Slf4j
public class FtpUtils {
    @Value("${upload.tempPath}")
    private String tempPath;

    public static String uploadTempPath;
    @PostConstruct
    public void setTempPath(){
        this.uploadTempPath=tempPath;
    }
    public static boolean downloadOaFileFromFtp(DaServerEntity oaFtpServer,String srcPath,
                                              String srcFileName,String destPath,String destFileName) throws FileNotFoundException {
        String localTempPath=uploadTempPath+System.currentTimeMillis();
        log.info("1111111111"+oaFtpServer.toString()+"-"+srcPath+"-"+srcFileName+"-"+destPath);
        System.out.println("2222222"+oaFtpServer.toString()+"-"+srcPath+"-"+srcFileName+"-"+destPath);
        if(!downloadFile(oaFtpServer,srcFileName,srcPath,localTempPath)){
            return false;
        }
        FileUtil.move(new File(localTempPath+"/"+srcFileName),new File(destPath),true);
        return true;
    }

    public static void main(String[] args) {
        DaServerEntity oaFtpServer=new DaServerEntity();
        oaFtpServer.setDiskname("/");
        oaFtpServer.setIpaddress("106.13.33.134");
        oaFtpServer.setPort(210);
        oaFtpServer.setPassword("@GQB012gqb");
        oaFtpServer.setUsername("Administrator");
        String remotePath="/InSheetID1578/";
        String filename="00000001.tif";
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(oaFtpServer.getIpaddress().trim(), oaFtpServer.getPort());
            log.info("oaFtp信息"+oaFtpServer.toString()+"---"+remotePath+filename);
            boolean loginResult= ftp.login(oaFtpServer.getUsername(), oaFtpServer.getPassword());
            log.info("ftp登录结果"+loginResult);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setControlEncoding(ftp.getCharset().toString());
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                log.info("ftp返回结果"+reply);
                ftp.disconnect();
            }
            String path=remotePath.replace("//","/");
            log.info("远程路径"+path);
            boolean result=false;
            File file=new File("/Users/guqianbin/Desktop/temp/ftpFile.tif");
            FileOutputStream fos=new FileOutputStream(file);
            result=ftp.changeWorkingDirectory(new String("/oaFile/InSheetID1578/".getBytes("utf-8"),"iso-8859-1"));
            ftp.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据

            if(!result){
                result=ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
                        "/"), "utf-8"));
                log.info("utf-8结果"+result);
            }
            if(!result){
                result = ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
                        "/"), "gbk"));
                log.info("GBK结果"+result);

            }
            if(!result){
                result =ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
                        "/"), "iso-8859-1"));
                log.info("iso-8859-1结果"+result);

            }
            if(!result){
                result =ftp.changeWorkingDirectory(remotePath);
                log.info("无编码结果"+result);

            }
            FTPFile[] files = ftp.listFiles();
            log.info(files.length+"文件长度");
            int i = 0;
            for (FTPFile ftpFile : files) {
                System.out.println(ftpFile.getName());
            }
            ftp.logout();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        log.info("文件拷贝结果"+success);

    }
    private static boolean downloadFile(DaServerEntity oaFtpServer, String filename,
                                       String remotePath, String localPath) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        if(oaFtpServer==null)
            return false;
        try {
            int reply;
            ftp.connect(oaFtpServer.getIpaddress().trim(), oaFtpServer.getPort());
			log.info("oaFtp信息"+oaFtpServer.toString()+"---"+remotePath+localPath+filename);
           boolean loginResult= ftp.login(oaFtpServer.getUsername(), oaFtpServer.getPassword());
           log.info("ftp登录结果"+loginResult);
           ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setControlEncoding(ftp.getCharset().toString());
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                log.info("ftp返回结果"+reply);
                ftp.disconnect();
                return success;
            }
            String path=oaFtpServer.getDiskname()+remotePath.replace("//","/");
            log.info("远程路径"+path);
            boolean result=false;
            if(!result){
                result=ftp.changeWorkingDirectory(
                        new String(path.getBytes("utf-8"),"iso-8859-1"));
                log.info("utf-8结果"+result);
            }
            if(!result){
                result=ftp.changeWorkingDirectory(
                        new String(path.getBytes("gbk"),"iso-8859-1"));

                log.info("GBK结果"+result);

            }
            if(!result){
                result=ftp.changeWorkingDirectory(
                        new String(path.getBytes("iso-8859-1"),"iso-8859-1"));

                log.info("iso-8859-1结果"+result);

            }
            ftp.enterLocalPassiveMode();  // 设置被动模式，开通一个端口来传输数据

            FTPFile[] files = ftp.listFiles();
            log.info(files.length+"文件长度");
            int i = 0;
            for (FTPFile ftpFile : files) {
                if (ftpFile.getName().toLowerCase().equals(filename.toLowerCase())) {
                    System.out.println(ftpFile.getName());
                    File locaFile = new File(localPath + "/" + filename);
                    if (!locaFile.getParentFile().exists())
                        locaFile.getParentFile().mkdirs();
                    OutputStream out = new FileOutputStream(locaFile);
                    log.info("获取文件"+ftp.retrieveFile(
                            new String(ftpFile.getName().getBytes(System.getProperty("file.encoding")),
                                    "iso-8859-1"), out));
                    out.close();
                    success = true;
                    log.info("获取的文件名字"+filename+"oaftp路径"+remotePath+"本地临时路径"+localPath);
                }
                i++;
            }
            ftp.logout();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return false;
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        log.info("文件拷贝结果"+success);
        return success;

    }

    private static String getPath(String path, String encodeingType)
            throws UnsupportedEncodingException {
        return new String(path.getBytes(System.getProperty("file.encoding")), encodeingType);
    }
}
